
import type { BytemdPlugin } from 'bytemd'
import themes from 'juejin-markdown-themes';
import {useMemo } from 'react';

function replaceTheme(text:string, newTheme:string) {
  // 使用正则表达式替换仅在开头出现的theme后面的内容
  if(text.startsWith('---\ntheme:')){
    return text.replace(/---\ntheme:.+?\n---\n/, `---\ntheme:${newTheme}\n---\n`);
  }

  return `---\ntheme:${newTheme}\n---\n${text}`
}
export default function themePlugin(setValue?:any): BytemdPlugin {

  const items = useMemo(()=>{
    return Object.keys(themes).map((item)=>{
      return (
        {
          title:'',
          icon:item,
          handler:{
            type: 'action',
            click:(ctx)=>{
              setValue( //添加前缀
                (oldV:string)=>{
                  return replaceTheme(oldV,item)
                }
              )
            }
          }
        }
      )
    })
  },[]) 
  return {
    actions: [
      {
        title: '',
        icon: '主题', // 16x16 SVG icon
        handler: {
          type: 'dropdown',
          actions:items
        },
      },
    ],
    viewerEffect({ file }: any) {
        if (file?.value==="")return     
        const $style = document.createElement('style')  
        try {        
            $style.innerHTML = themes[file?.frontmatter?.replace('theme:',"")]?.style ?? themes.juejin.style
        }
        catch (e) {
        $style.innerHTML = themes.juejin.style
        }
        document.querySelector('.markdown-body')?.appendChild($style)
      return () => {
        $style.remove()
      }
    }     
  }
}